package com.yz.xyt.filter;

import com.yz.xyt.domain.LoginUser;
import com.yz.xyt.service.IAppManagerService;
import com.yz.xyt.utils.JwtUtil;
import com.yz.xyt.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 认证过滤器
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private RedisCache redisCache;
    @Autowired
    IAppManagerService appManagerService;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token,从请求头中获取
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
            filterChain.doFilter(request,response);
            return;
        }

        //解析token
        Claims claims = jwtUtil.parseToken(token);
        //登录的身份
        String subject = claims.getSubject();
        List<String> subjectInfo = Arrays.asList(subject.split("_"));
        //用户id
        String userId = subjectInfo.get(0);
        //登录传递的系统版本
        String version = subjectInfo.get(1);
        //登录用户的类型 1：app用户，0：后端用户
        String userType = subjectInfo.get(2);

        //系统中的版本号
        String systemVersion = appManagerService.findAppVersion().getAppVersion();
        //app用户验证版本号
        if ("1".equals(userType)){
            if(!systemVersion.equals(version)){
                filterChain.doFilter(request,response);
                return;
            }
        }

        //获取redis存储用户信息的key
        String redisKey = "login:" + userId;
        LoginUser loginUser = redisCache.getCacheObject(redisKey);

        //redis中不存在登录用户，直接过滤
        if(Objects.isNull(loginUser)){
           filterChain.doFilter(request,response);
           return;
        }
        //存入SecurityContextHolder
        //获取用户权限
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request,response);
    }
}
